import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:my_app_01/api/list.dart';
import 'package:my_app_01/api/order.dart';
import 'package:my_app_01/components/AppBarSearch.dart';
import 'package:my_app_01/components/ListItemCard.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class ListPage extends StatefulWidget {
  String pageTitle;

  ListPage({super.key, this.pageTitle = ""});

  @override
  State<ListPage> createState() => _ListPageState();
}

class _ListPageState extends State<ListPage> {
  List items = [];
  int page = 1;
  int size = 5;

  @override
  void initState() {
    super.initState();
    getList();
  }

  final RefreshController _refreshController = RefreshController(initialRefresh: false);

  void _onRefresh() async {
    page = 1;
    size = 5;
    await getList();
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    page += 1;
    await getList();
    _refreshController.loadComplete();
  }

  Future<List> getList() async {
    EasyLoading.show(status: "加载中...");
    var data = await OrderApi.getList({"pageNo": page, "pageSize": size});
    print(data?['data']);
    List result = data?['data']?['rows'] ?? [];
    EasyLoading.dismiss();
    if (page == 1) {
      items = result;
    } else {
      items.addAll(result);
    }
    if (mounted) {
      setState(() {});
    }
    return result;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: const Size.fromHeight(60),
        child: AppBarSearch(
          onSearch: (value) {
            print(value);
          },
        ),
      ),
      body: Container(
        child: SmartRefresher(
          enablePullUp: true,
          controller: _refreshController,
          onRefresh: _onRefresh,
          onLoading: _onLoading,
          child: ListView.builder(
            padding: const EdgeInsets.only(left: 15, right: 15, bottom: 20),
            itemCount: items.length,
            itemBuilder: (BuildContext context, int index) {
              var currentItem = items.elementAt(index);
              return ListItemCard(
                title: Text(
                  "${currentItem['code']}",
                  style: ListItemCard.defaultTitleStyle,
                ),
                childrenProps: [
                  {"label": "订单总额", "value": currentItem['totalmoney']},
                  {"label": "采购用户", "value": currentItem['orderusername']},
                  {"label": "采购时间", "value": currentItem['ordertime']},
                  {"label": "供应商", "value": currentItem['suppliername']},
                  {"label": "期望送达", "value": currentItem['expectedtime']}
                ],
              );
            },
          ),
        ),
      ),
    );
  }
}
